package com.elitel.frame.base.service.impl;

import com.elitel.common.utils.SpringUtils;
import com.elitel.common.utils.UUIDUtil;
import com.elitel.common.utils.XCommonUtils;
import com.elitel.frame.base.component.RedisCacheDataBase;
import com.elitel.frame.base.component.exportprojectdata.DataBaseConnInfo;
import com.elitel.frame.base.service.BaseFieldenumService;
import com.elitel.frame.base.service.BaseQueryfieldService;
import com.elitel.frame.base.service.BaseQueryfieldcacheService;
import com.elitel.frame.base.service.BaseQuerysqlService;
import com.elitel.frame.main.dao.*;
import com.elitel.frame.main.dao.ext.*;
import com.elitel.frame.main.entity.*;
import com.elitel.frame.main.entity.ext.BaseFieldaddonsExt;
import com.elitel.frame.main.entity.ext.BaseQueryfieldExt;
import com.elitel.frame.main.entity.ext.BaseQueryfieldcacheExt;
import com.elitel.frame.main.entity.ext.QueryFiled;
import com.elitel.frame.main.entity.vo.BaseQueryFieldVo;
import com.elitel.frame.main.entity.vo.PageRequestVo;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.elitel.frame.main.entity.vo.QueryFieldVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author guoyanfei
 * @description 设置服务查询字段服务接口实现
 */
@Service
public class BaseQueryfieldServiceImpl implements BaseQueryfieldService {
    @Autowired
    private ExtCfgTableMapper extCfgTableMapper;
    @Autowired
    private ExtCfgFieldMapper extCfgFieldMapper;
    @Autowired
    private ExtBaseFieldconfigMapper extBaseFieldconfigMapper;
    @Autowired
    private ExtBaseFieldaddonsMapper extBaseFieldaddonsMapper;
    @Autowired
    private CfgFieldMapper cfgFieldMapper;
    @Autowired
    private BaseQueryfieldMapper baseQueryfieldMapper;
    @Autowired
    private ExtBaseQueryfieldMapper extBaseQueryfieldMapper;
    @Autowired
    private RedisCacheDataBase redisCacheDataBase;
    @Autowired
    private CfgExtendMapper cfgExtendMapper;
    @Autowired
    private CfgExtmasterMapper cfgExtmasterMapper;
    @Autowired
    private BaseQuerysqlService baseQuerysqlService;
    @Autowired
    private BaseFieldaddonsMapper baseFieldaddonsMapper;
    @Autowired
    private BaseFieldenumService baseFieldenumService;
    @Autowired
    private BaseFieldenumMapper baseFieldenumMapper;
    @Autowired
    private DataBaseConnInfo dataBaseConnInfo;
    @Autowired
    private BaseQueryfieldcacheService baseQueryfieldcacheService;
    @Autowired
    private BaseQueryfieldcacheMapper baseQueryfieldcacheMapper;
    @Autowired
    private ExtBaseQueryfieldcacheMapper extBaseQueryfieldcacheMapper;

    @Resource
    private ExtBaseTreeconfigMapper extBaseTreeconfigMapper;

    @Override
    public List<QueryFieldVo> getAllFieldBydtConfigId(String dtConfigId) {
        List<QueryFieldVo> queryFieldVos = new ArrayList<>();
        CfgTable cfgTable = extCfgTableMapper.getInfoByDtconfigId(dtConfigId);
        if (cfgTable != null) {
            if (cfgTable.getDtTabletype() == 1) { // 数据表
                queryFieldVos = getTableField(dtConfigId, cfgTable, "AA");
            } else if (cfgTable.getDtTabletype() == 2) { // 视图
                queryFieldVos = getViewField(dtConfigId, cfgTable);
            }
        }
        return queryFieldVos;
    }

    /**
     * @param dtConfigId
     * @return QueryFieldVo集合
     * @description 查询单表字段
     * @author guoyanfei
     */
    private List<QueryFieldVo> getTableField(String dtConfigId, CfgTable cfgTable, String alterName) {
        List<QueryFieldVo> queryFieldVos = new ArrayList<>();
        List<CfgField> cfgFields = extCfgFieldMapper.getAllFieldList(dtConfigId);
        if (cfgFields != null) {
            for (CfgField cfgField : cfgFields) {
                QueryFieldVo queryFieldVo = new QueryFieldVo();
                queryFieldVo.setTableNameCn(cfgTable.getDtNameCn());
                queryFieldVo.setTableAlterName(alterName);
                queryFieldVo.setFieldguid(cfgField.getGuid());
                queryFieldVo.setFieldName(cfgField.getDfName());
                queryFieldVo.setFieldNameCn(cfgField.getDfNameCn());
                queryFieldVos.add(queryFieldVo);
            }
        }
        // 字段枚举
        List<BaseFieldenum> baseFieldenums = baseFieldenumService.getBaseFieldenumList(dtConfigId);
        if (baseFieldenums != null && baseFieldenums.size() > 0) {
            for (BaseFieldenum baseFieldenum : baseFieldenums) {
                QueryFieldVo queryFieldVo = new QueryFieldVo();
                queryFieldVo.setTableNameCn(cfgTable.getDtNameCn());
                queryFieldVo.setTableAlterName(alterName);
                queryFieldVo.setFieldguid(baseFieldenum.getGuid());
                queryFieldVo.setFieldName(baseFieldenum.getEnumcode());
                queryFieldVo.setFieldNameCn(baseFieldenum.getEnumname());
                queryFieldVos.add(queryFieldVo);
            }
        }
        return queryFieldVos;
    }

    /**
     * @param dtConfigId
     * @param cfgTable
     * @return QueryFieldVo集合
     * @description 查询视图字段
     * @author guoyanfei
     */
    private List<QueryFieldVo> getViewField(String dtConfigId, CfgTable cfgTable) {
        List<QueryFieldVo> queryFieldVos = new ArrayList<>();
        List<BaseFieldaddonsExt> baseFieldaddonsExts =
                extBaseFieldaddonsMapper.getBaseFieldaddonsByPage(dtConfigId);
        if (baseFieldaddonsExts != null && baseFieldaddonsExts.size() > 0) {
            short ismodfn = 1;
            for (BaseFieldaddonsExt baseFieldaddonsExt : baseFieldaddonsExts) {
                QueryFieldVo queryFieldVo = new QueryFieldVo();
                queryFieldVo.setFieldguid(baseFieldaddonsExt.getGuid());
                if (baseFieldaddonsExt.getIsmodfname() != null
                        && baseFieldaddonsExt.getIsmodfname().equals(ismodfn)) {
                    queryFieldVo.setFieldName(baseFieldaddonsExt.getModifieldname());
                } else {
                    queryFieldVo.setFieldName(baseFieldaddonsExt.getFieldname());
                }
                if (baseFieldaddonsExt.getIsmodfcaption() != null
                        && baseFieldaddonsExt.getIsmodfcaption().equals(ismodfn)) {
                    queryFieldVo.setFieldNameCn(baseFieldaddonsExt.getModifieldcaption());
                } else {
                    queryFieldVo.setFieldNameCn(baseFieldaddonsExt.getFieldnameCn());
                }
                queryFieldVo.setTableAlterName(baseFieldaddonsExt.getAltername());
                queryFieldVo.setTableNameCn(cfgTable.getDtNameCn());
                queryFieldVos.add(queryFieldVo);
            }
        }
        return queryFieldVos;
    }

    @Override
    public Integer insertBaseQueryfield(
            String strFields, String serviceId, Integer serviceType, String grade, Integer paramType) {
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer result = 0;
        String fieldid = "";
        String fieldName = "";
        String[] fields = strFields.split("@");
        if (fields.length > 0) {
            int i = 1;
            Integer maxorder = 0;
            String databaseType = dataBaseConnInfo.dataBaseType;
            maxorder = getMaxOrder(serviceId, serviceType, grade, paramType, maxorder, databaseType);

            if (maxorder != null) {
                i = maxorder + 1;
            }
            for (String str : fields) {
                // 查询字段Code
                BaseFieldaddons baseFieldaddons = baseFieldaddonsMapper.selectByPrimaryKey(str);
                if (baseFieldaddons != null) {
                    fieldid = baseFieldaddons.getFieldid();
                } else {
                    fieldid = str;
                }
                CfgField cfgField = cfgFieldMapper.selectByPrimaryKey(fieldid);
                if (cfgField != null) {
                    // 字段
                    fieldName = cfgField.getDfName();
                } else {
                    // 枚举
                    BaseFieldenum baseFieldenum = baseFieldenumMapper.selectByPrimaryKey(fieldid);
                    if (baseFieldenum != null) {
                        fieldName = baseFieldenum.getEnumcode();
                    }
                }
                // 创建实体
                BaseQueryfield baseQueryfield = new BaseQueryfield();
                String guid = UUID.randomUUID().toString();
                baseQueryfield.setGuid(guid);
                baseQueryfield.setServiceid(serviceId);
                baseQueryfield.setServicetype(serviceType);
                baseQueryfield.setQueryorder(i);
                baseQueryfield.setShowtype(0);
                baseQueryfield.setRemark("");
                baseQueryfield.setCreatedate(new Date());
                baseQueryfield.setFieldaddonsguid(str);
                baseQueryfield.setGrade(grade);
                baseQueryfield.setParametertype(paramType);
                baseQueryfield.setParametercondition("=");
                // paramType 1: dynamic 2: static
                if (paramType.equals(1)) {
                    if (XCommonUtils.isOriginSingleTableType(serviceType)) {
                        baseQueryfield.setParametercode(fieldName);

                    } else {
                        baseQueryfield.setParametercode("param_" + fieldName + "_" + getRandomString(4));
                    }
                } else if (paramType.equals(2)) {
                    baseQueryfield.setParametervalue("1");
                }
                baseQueryfield.setParamformat("string");
                result += baseQueryfieldMapper.insertSelective(baseQueryfield);
                // 如果条件缓存配置存在则添加相应的缓存配置
                insertQueryFieldCache(serviceId, "singleTableServer", guid);
                i++;
            }
        }
        if (result > 0) {
            // 更新条件缓存配置

            // 刷新服务
            redisCacheDataBase.refreshBaseQueryfield(serviceId, String.valueOf(serviceType), grade);
            // 更新SQL文
            baseQuerysqlService.editBaseQuerysql(serviceId, String.valueOf(serviceType), grade);
        }
        return result;
    }

    //@Override
    public Integer addBaseQueryfieldBySqlConditionType(List<BaseQueryfield> baseQueryFieldList, Integer sqlConditionType) {
        if (XCommonUtils.isEmpty(baseQueryFieldList))
            return 0;

        BaseQueryfield baseQueryfield = baseQueryFieldList.get(0);
        String serviceId = baseQueryfield.getServiceid();
        Integer serviceType = baseQueryfield.getServicetype();
        String grade = baseQueryfield.getGrade();

//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer result = 0;
        String fieldid = "";
        String fieldName = "";
        int queryOrder = 1;
        Integer maxorder = 0;
        String databaseType = dataBaseConnInfo.dataBaseType;
        // 查询最大排序序号
        maxorder = getMaxOrder(serviceId, serviceType, grade, sqlConditionType, maxorder, databaseType);

        if (maxorder != null)
            queryOrder = maxorder + 1;

        for (BaseQueryfield baseQueryField : baseQueryFieldList) {
            String fieldGuid = baseQueryField.getFieldaddonsguid();
            // 查询字段Code
            BaseFieldaddons baseFieldaddons = baseFieldaddonsMapper.selectByPrimaryKey(fieldGuid);
            if (baseFieldaddons != null) {
                fieldid = baseFieldaddons.getFieldid();
            } else {
                fieldid = fieldGuid;
            }
            CfgField cfgField = cfgFieldMapper.selectByPrimaryKey(fieldid);
            if (cfgField != null) {
                // 字段
                fieldName = cfgField.getDfName();
            } else {
                // 枚举
                BaseFieldenum baseFieldenum = baseFieldenumMapper.selectByPrimaryKey(fieldid);
                if (baseFieldenum != null) {
                    fieldName = baseFieldenum.getEnumcode();
                }
            }
            // 创建实体
            String guid = UUID.randomUUID().toString();
            baseQueryField.setGuid(guid);
            baseQueryField.setQueryorder(queryOrder);
            baseQueryField.setCreatedate(new Date());
            baseQueryField.setFieldaddonsguid(fieldGuid);
            baseQueryField.setParametertype(sqlConditionType);

            if (XCommonUtils.isEmpty(baseQueryField.getParametercondition()))
                baseQueryField.setParametercondition("=");

            // paramType 1: dynamic condition 2: static condition
            if (XCommonUtils.isEmpty(baseQueryField.getParametercode())) {
                // here is support custom condition variable name
                if (XCommonUtils.isOriginSingleTableType(serviceType)) {
                    baseQueryField.setParametercode(fieldName);
                } else {
                    baseQueryField.setParametercode("param_" + fieldName + "_" + getRandomString(4));
                }
            }
            // static sql condition need default value
            if (sqlConditionType.equals(2) && XCommonUtils.isEmpty(baseQueryfield.getParametervalue()))
                baseQueryField.setParametervalue("1");

            baseQueryField.setParamformat("string");
            result += baseQueryfieldMapper.insertSelective(baseQueryField);
            // 如果条件缓存配置存在则添加相应的缓存配置
            insertQueryFieldCache(serviceId, "singleTableServer", guid);
            queryOrder++;
        }

        if (result > 0) {
            // 更新条件缓存配置

            // 刷新服务
            redisCacheDataBase.refreshBaseQueryfield(serviceId, String.valueOf(serviceType), grade);
            // 更新SQL文
            baseQuerysqlService.editBaseQuerysql(serviceId, String.valueOf(serviceType), grade);
        }
        return result;
    }

    private Integer getMaxOrder(String serviceId, Integer serviceType, String grade, Integer paramType, Integer maxorder,
                                String databaseType) {
       /*switch (databaseType) {
            case "oracle":
                maxorder = extBaseQueryfieldMapper.selectMaxShowOrderOracle(serviceId, serviceType, paramType, grade);
                break;
            case "mysql":
            case "sqlite":
            case "h2":
            case DataSourceType.POSTGRES:
                maxorder = extBaseQueryfieldMapper.selectMaxShowOrderMysql(serviceId, serviceType, paramType, grade);
                break;
        }*/
        maxorder = extBaseQueryfieldMapper.selectMaxShowOrderMysql(serviceId, serviceType, paramType, grade);
        return maxorder;
    }

    private Integer insertQueryFieldCache(
            String serviceId, String serviceType, String fieldaddonsguid) {
        Integer size = 0;
        List<BaseQueryfieldcacheExt> cachegroup =
                baseQueryfieldcacheService.queryCacheFieldGroup(serviceId, serviceType);
        if (cachegroup == null || cachegroup.size() <= 0) return size;
        for (BaseQueryfieldcacheExt fieldcache : cachegroup) {
            BaseQueryfieldcache baseQueryfieldcache = new BaseQueryfieldcache();
            baseQueryfieldcache.setGuid(UUID.randomUUID().toString());
            baseQueryfieldcache.setFieldaddonsguid(fieldaddonsguid);
            baseQueryfieldcache.setParametergroup(fieldcache.getParametergroup());
            size += baseQueryfieldcacheMapper.insertSelective(baseQueryfieldcache);
            // 刷新热配任务 调度
        }

        return size;
    }

    /**
     * * show 随机生成字符串 create by guoyanfei on 2018/12/18
     *
     * @param length 字符串长度
     * @return 字符串
     */
    private String getRandomString(Integer length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int num = random.nextInt(52);
            sb.append(str.charAt(num));
        }

        return sb.toString();
    }

    @Override
    public PageResponseVo<BaseQueryfield> getListByPage(
            PageRequestVo<BaseQueryfield> pr, String serviceId, Integer serviceType) {
        PageResponseVo<BaseQueryfield> baseQueryfield = new PageResponseVo<BaseQueryfield>();
        pr.StartPage();
        List<BaseQueryfield> bq =
                extBaseQueryfieldMapper.getAllList(pr.beginRow, pr.endRow, serviceId, serviceType);
        Integer count = extBaseQueryfieldMapper.getListCount(serviceId, serviceType);
        baseQueryfield.setTotal(count);
        baseQueryfield.setRows(bq);
        return baseQueryfield;
    }

    @Override
    public Integer deleteQueryfield(String guids) {
        Integer result = 0;
        BaseQueryfield baseQueryfield = new BaseQueryfield();
        List<String> listguid = Arrays.asList(guids.split("@"));
        if (listguid != null && listguid.size() > 0) {
            baseQueryfield = baseQueryfieldMapper.selectByPrimaryKey(listguid.get(0));
        }
        result = extBaseQueryfieldMapper.deleteBatchByguid(listguid);
        if (result > 0) {
            // 更新条件缓存配置
            Integer size = extBaseQueryfieldcacheMapper.deleteQueryFieldCacheByFieldaddonsguid(listguid);
            // 刷新服务
            redisCacheDataBase.refreshBaseQueryfield(
                    baseQueryfield.getServiceid(),
                    baseQueryfield.getServicetype().toString(),
                    baseQueryfield.getGrade());
            // 更新SQL文
            baseQuerysqlService.editBaseQuerysql(
                    baseQueryfield.getServiceid(),
                    baseQueryfield.getServicetype().toString(),
                    baseQueryfield.getGrade());
        }
        return result;
    }

    @Override
    public Integer updateQueryfield(BaseQueryfield baseQueryfield) {
        Integer result = 0;
        result = baseQueryfieldMapper.updateByPrimaryKeySelective(baseQueryfield);
        if (result > 0) {
            // 更新条件缓存配置

            // 刷新服务
            redisCacheDataBase.refreshBaseQueryfield(
                    baseQueryfield.getServiceid(),
                    baseQueryfield.getServicetype().toString(),
                    baseQueryfield.getGrade());
            // 更新SQL文
            baseQuerysqlService.editBaseQuerysql(
                    baseQueryfield.getServiceid(),
                    baseQueryfield.getServicetype().toString(),
                    baseQueryfield.getGrade());
        }
        return result;
    }

    @Override
    public Integer batchUpdateQueryfieldList(List<BaseQueryfield> baseQueryfieldList) {
        int count = 0;

        for (BaseQueryfield baseQueryfield : baseQueryfieldList) {
            Integer result = baseQueryfieldMapper.updateByPrimaryKeySelective(baseQueryfield);
            if (result > 0) {
                // 刷新服务
                redisCacheDataBase.refreshBaseQueryfield(baseQueryfield.getServiceid(), baseQueryfield.getServicetype().toString(), baseQueryfield.getGrade());
                // 更新SQL文
                baseQuerysqlService.editBaseQuerysql(baseQueryfield.getServiceid(), baseQueryfield.getServicetype().toString(), baseQueryfield.getGrade());
            }
            count += result;
        }
        return count;
    }


    @Override
    public List<BaseQueryfield> getQueryFieldByServiceId(String serviceId, Integer serviceType) {
        return extBaseQueryfieldMapper.getBaseQueryfieldbyServiceId(serviceId, serviceType);
    }

    @Override
    public List<BaseQueryfieldExt> getQueryFieldListByServiceId(
            String serviceId, String serviceType, String grade, Integer paramType) {
        String databaseType = dataBaseConnInfo.dataBaseType;
        List<BaseQueryfieldExt> baseQueryfieldExts = new ArrayList<BaseQueryfieldExt>();
        String dtConfigId = "";
        if (XCommonUtils.isSingleTableService(serviceType)) {
            // 单表服务
            CfgExtend cfgExtend = cfgExtendMapper.selectByPrimaryKey(serviceId);
            if (cfgExtend != null) {
                dtConfigId = cfgExtend.getDtConfigId();
            }

        } else if (XCommonUtils.isMasterSlaveTableService(serviceType)) {
            // 主从表服务
            CfgExtmaster cfgExtmaster = cfgExtmasterMapper.selectByPrimaryKey(serviceId);
            if (cfgExtmaster != null) {
                dtConfigId = cfgExtmaster.getDtConfigId();
            }
        } else if (XCommonUtils.isResourceTreeService(serviceType)) {
            // 资源树
            BaseTreeconfig baseTreeconfig = selectTreeConfigOne(serviceId, grade);
            if (baseTreeconfig != null) {
                dtConfigId = baseTreeconfig.getDtConfigId();
            }
        }

        if (XCommonUtils.isEmpty(dtConfigId))
            return baseQueryfieldExts;

        CfgTable cfgTable = extCfgTableMapper.getInfoByDtconfigId(dtConfigId);
        if (cfgTable == null)
            return baseQueryfieldExts;

        if (XCommonUtils.isOriginSingleTableType(cfgTable.getDtTabletype())) {
            // 数据表
            /*switch (databaseType) {
                case "oracle":
                    baseQueryfieldExts =
                            extBaseQueryfieldMapper.getBaseQueryfieldtoTableList(
                                    serviceId, Integer.valueOf(serviceType), grade, paramType);
                    break;
                case "mysql":
                case "sqlite":
                case "h2":
                case DataSourceType.POSTGRES:
                    baseQueryfieldExts =
                            extBaseQueryfieldMapper.getBaseQueryfieldtoTableListMysql(
                                    serviceId, Integer.valueOf(serviceType), grade, paramType);
                    break;
            }*/
            baseQueryfieldExts = extBaseQueryfieldMapper.getBaseQueryfieldtoTableListMysql(serviceId, Integer.valueOf(serviceType), grade, paramType);
        } else if (XCommonUtils.isViewTableType(cfgTable.getDtTabletype())) {
            // 视图
            /*switch (databaseType) {
                case "oracle":
                    baseQueryfieldExts =
                            extBaseQueryfieldMapper.getBaseQueryfieldtoViewList(
                                    serviceId, Integer.valueOf(serviceType), grade, paramType);
                    break;
                case "mysql":
                case "sqlite":
                case "h2":
                case DataSourceType.POSTGRES:
                    baseQueryfieldExts =
                            extBaseQueryfieldMapper.getBaseQueryfieldtoViewListMysql(
                                    serviceId, Integer.valueOf(serviceType), grade, paramType);
                    break;
            }*/
            baseQueryfieldExts =  extBaseQueryfieldMapper.getBaseQueryfieldtoViewListMysql(serviceId, Integer.valueOf(serviceType), grade, paramType);
        }

        return baseQueryfieldExts;
    }

    /**
     * 内部调用，并非实现
     *
     * @param guid
     * @param grade
     * @return
     * @author dingdaifu
     */
    private BaseTreeconfig selectTreeConfigOne(String guid, String grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("grade", grade);
        BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectTreeConfigOne(map);
        return baseTreeconfig;
    }

    @Override
    public BaseQueryfieldExt getQueryFieldByParamCode(String dataservercode, String parmetercode) {
        BaseQueryfieldExt baseQueryfieldExt =
                extBaseQueryfieldMapper.getQueryFieldByParamCode(dataservercode, parmetercode);
        return baseQueryfieldExt;
    }

    @Override
    public BaseQueryfield getQueryFieldByGuid(String fieldaddonsguid) {
        BaseQueryfield baseQueryfield = baseQueryfieldMapper.selectByPrimaryKey(fieldaddonsguid);
        return baseQueryfield;
    }

    @Override
    public SysPrjservice getServiceByFieldGuid(String guid) {
        SysPrjservice baseQueryfieldExt = extBaseQueryfieldMapper.getServiceByFieldGuid(guid);
        return baseQueryfieldExt;
    }

    /**
     * TODO: 批量添加查询字段
     *
     * @param baseQueryfields
     * @return
     */
    @Override
    public Integer batchInsertBaseQueryField(List<BaseQueryfield> baseQueryfields) {
        if (dataBaseConnInfo.dataBaseType.equals("sqlite")) {
            return extBaseQueryfieldMapper.batchInsertBaseQueryFieldSqlite(baseQueryfields);
        }
        return extBaseQueryfieldMapper.batchInsertBaseQueryField(baseQueryfields);
    }

    /**
     * show 通过服务ID删除其查询字段信息
     *
     * @param serviceId(服务ID)
     * @return 删除条数
     * @author guoyanfei
     * @date 2017/11/08
     */
    @Override
    public Integer deleteQueryfieldByServiceId(String serviceId) {
        return extBaseQueryfieldMapper.deleteQueryfieldByServiceId(serviceId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<BaseQueryfield> saveQueryFiled(List<BaseQueryfield> list) {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }

        ArrayList<BaseQueryfield> res = new ArrayList<>();
        String serviceid = list.get(0).getServiceid();
        List<BaseQueryfield> dbDatas = extBaseQueryfieldMapper.selectByServiceCode(serviceid);
        Map<String, String> paramCodeGuidMap = dbDatas.stream().collect(Collectors.toMap(BaseQueryfield::getParametercode, BaseQueryfield::getGuid, (k1, k2) -> k1));
        Set<String> paramCodeSet = list.stream().map(BaseQueryfield::getParametercode).collect(Collectors.toSet());

        // 要兼容不同的数据库 循环新增更新
        for (BaseQueryfield baseQueryfield : list) {
            String guid = paramCodeGuidMap.get(baseQueryfield.getParametercode());
            if (StringUtils.isNotBlank(guid)) {
                baseQueryfield.setGuid(guid);
                baseQueryfieldMapper.updateByPrimaryKeySelective(baseQueryfield);
                res.add(baseQueryfield);
            } else {
                BaseQueryfield iData = new BaseQueryfield();
                iData.setGuid(UUIDUtil.randomUUID());
                iData.setServiceid(baseQueryfield.getServiceid());
                iData.setParametercode(baseQueryfield.getParametercode());
                // todo 这里不确定前端有没有传值
                iData.setServicetype(baseQueryfield.getServicetype());
                iData.setRequiredFlag(baseQueryfield.getRequiredFlag());
                baseQueryfieldMapper.insertSelective(iData);
                res.add(iData);
            }


        }

        // 删除多余数据
        ArrayList<String> deleteGuidList = new ArrayList<>();
        for (String dbParams : paramCodeGuidMap.keySet()) {
            if (!paramCodeSet.contains(dbParams)) {
                deleteGuidList.add(paramCodeGuidMap.get(dbParams));
            }
        }
        if (!CollectionUtils.isEmpty(deleteGuidList)) {
            extBaseQueryfieldMapper.deleteBatchByguid(deleteGuidList);
        }
        return res;
    }

    @Override
    public void selectQueryFiled(String serviceCode, List<BaseQueryfieldExt> baseQueryfieldExts) {
        try {
            List<BaseQueryfield> baseQueryfields = extBaseQueryfieldMapper.selectByServiceCode(serviceCode);
            Set<String> collect = baseQueryfields.stream().filter(item -> "1".equals(item.getRequiredFlag())).map(BaseQueryfield::getParametercode).collect(Collectors.toSet());
            for (BaseQueryfieldExt ext : baseQueryfieldExts) {
                if (collect.contains(ext.getParametercode())) {
                    ext.setRequiredFlag("1");
                } else {
                    ext.setRequiredFlag("0");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void selectSqlRequiredFields(String serviceCode, List<QueryFiled> queryFileds) {
        try {
            List<BaseQueryfield> baseQueryfields = extBaseQueryfieldMapper.selectByServiceCode(serviceCode);
            Set<String> collect = baseQueryfields.stream().filter(item -> "1".equals(item.getRequiredFlag())).map(BaseQueryfield::getParametercode).collect(Collectors.toSet());
            for (QueryFiled ext : queryFileds) {
                if (collect.contains(ext.getParametercode())) {
                    ext.setRequiredFlag("1");
                }else {
                    ext.setRequiredFlag("0");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Set<String> selectRequiredFieldsByServiceGuid(String guid) {
        SysPrjserviceMapper bean = SpringUtils.getBean(SysPrjserviceMapper.class);
        SysPrjservice sysPrjservice = bean.selectByPrimaryKey(guid);
        List<BaseQueryfield> baseQueryfields = extBaseQueryfieldMapper.selectByServiceCode(sysPrjservice.getServicecode());
        return baseQueryfields.stream().filter(item -> "1".equals(item.getRequiredFlag())).map(BaseQueryfield::getParametercode).collect(Collectors.toSet());
    }

    @Override
    public List<BaseQueryFieldVo> selectByServiceCodes(List<String> serviceCodes) {
       return baseQueryfieldMapper.selectByServiceCodes(serviceCodes);
    }

    @Override
    public List<BaseQueryFieldVo> selectExecuteByServiceCodes(List<String> serviceCodes) {
        return baseQueryfieldMapper.selectExecuteByServiceCodes(serviceCodes);
    }
}
